from sqlalchemy import and_
from flask import Blueprint, request
from models import *
from flask_jwt_extended import verify_jwt_in_request

return_data = Blueprint('return_data', __name__)


@return_data.route('/api/getByCategory', methods=['GET'])
def getByCategory():
    permission = 0
    try:
        verify_jwt_in_request(refresh=True)
        permission = 1
    except:
        pass
    category = request.args.get("category")
    if category is None:
        return "{'code':-1, 'msg':'目录错误'}"
    place = request.args.get('place', default='All')

    result = dict()
    if place == 'All':
        infoes = Devices.query.filter(and_(Devices.category == category, Devices.permission <= permission)).all()
    else:
        infoes = Devices.query.filter(
            and_(Devices.category == category, Devices.permission <= permission, Devices.place == place)).all()
    for i in infoes:
        if not result.__contains__(i.name):
            detail = dict()
            result[i.name] = detail
            detail['family'] = i.family.split(' ')
            if '' in detail['family']:
                detail['family'].remove('')
            detail['tag'] = i.tag
            detail['status'] = dict()
        result[i.name]['status'][str(i.id)] = i.state
    return result


@return_data.route('/api/lowPermission', methods=['GET'])
def lowPermission():
    result = dict()
    infoes = Devices.query.filter(and_(Devices.permission == 0)).all()
    for i in infoes:
        if not result.__contains__(i.name):
            detail = dict()
            result[i.name] = detail
            detail['family'] = i.family.split(' ')
            if '' in detail['family']:
                detail['family'].remove('')
            detail['tag'] = i.tag
            detail['status'] = dict()
        result[i.name]['status'][str(i.id)] = i.state
    return result
